<?php
namespace app\index\controller;

use app\common\controller\Base;
use app\index\controller\Menu;
use think\Request;

/**
 * 角色控制器
 */
class Role extends Base
{

    protected $model;

    /**
     * 控制器初始化
     * @return   void
     */
    public function _initialize()
    {
        //基类授权
        //
        parent::_initialize();
        $this->model = new \app\index\model\Role();
    }
    /**
     * 角色列表
     * @DateTime 2018-02-12
     * @return   [type]
     */
    public function doList(Request $request)
    {
        $res = $this->model->doList();
        _callback($res);
    }

    /**
     * 角色菜单权限描述更新
     */
    public function doDescUpdate(Request $request)
    {
        try {

            $res            = $this->model->doUpdate($request);
            $output['data'] = $res;

            if ($res) {
                $output['success'] = true;
            } else {
                $output['success'] = false;
            }

            $output['msg'] = $res ? '更新成功' : '更新失败';

            return json($output);

        } catch (\Exception $e) {
            //$this->doLog($e->getMessage());
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 角色菜单权限更新
     */
    public function doupdate()
    {

        $menu_ids     = $this->request->param('menu_ids');
        $menu_ids_arr = json_decode($menu_ids);

        $temp = $menu_ids_arr;

        foreach ($menu_ids_arr as $v) {

            $menu = new Menu();

            // 获取子菜单的父ID，如果权限菜单数组里面尚无则添加到权限菜单数组

            $pid = $menu->getParentId($v);

            //过滤pid = null的字段
            if (!in_array($pid, $temp) && !empty($pid)) {

                array_push($temp, $pid);
            }

        }

        //角色数据模型更新数据
        $param             = $this->request->param();
        $param['menu_ids'] = implode(',', $temp);

        $res = $this->model->doUpdateByArr($param);

        $output['data'] = $res;

        if ($res) {
            $output['success'] = true;
        } else {
            $output['success'] = false;
        }
        $output['msg'] = $res ? '更新成功' : '更新失败';

        _callback($output);
    }
}
